<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Chat</title>
    <link rel="stylesheet" type="text/css" th:href="@{/lib/layui/css/layui.css}" />
    <link rel="stylesheet" type="text/css" th:href="@{/css/style.css}" />
</head>
<body>

<div class="chat-container">
    <div class="chat-content">
        <ul class="layui-timeline" id="message-list">
        </ul>
    </div>
    <div class="chat-footer">
        <button id="clear-button" class="layui-btn layui-btn-sm layui-btn-primary layui-border-red" style="float:left;">
            <i class="layui-icon layui-icon-delete"></i>
        </button>
        <button id="send-button" class="layui-btn layui-btn-sm layui-btn-primary layui-border-blue layui-btn-disabled" style="float:right;">
            <i class="layui-icon layui-icon-release"></i>
        </button>
        <textarea id="message" placeholder="请输入内容" class="layui-textarea"></textarea>
    </div>
</div>

<script th:src="@{/lib/layui/layui.js}"></script>
<script th:src="@{/js/chat.js}"></script>
<script th:inline="javascript">
    const OPENAI_API_KEY = [[${apiKey}]];

    layui.use(['jquery', 'layer'], function() {
        const $ = layui.$;

        const $chatContent = $(".chat-content");
        const $messageList = $("#message-list");
        const $message = $("#message");
        const $sendButton = $("#send-button");
        const $clearButton = $("#clear-button");

        $message.on('input', function() {
            if ($message.val().trim() === '') {
                $sendButton.addClass("layui-btn-disabled");
            } else {
                $sendButton.removeClass("layui-btn-disabled");
            }
        });

        $sendButton.on('click', function() {
            const content = $message.val().trim();
            if (content !== '') {
                sendMessage(content);
            }
        });

        $clearButton.on('click', function() {
            $messageList.empty();
        });

        function sendMessage(content) {
            $messageList.append(`
                <li class="layui-timeline-item">
                  <i class="layui-icon layui-icon-circle"></i>
                  <div class="layui-timeline-content layui-text chat-user-message">
                    <h3 class="layui-timeline-title">
                        <i class="layui-icon layui-icon-friends"></i>
                    </h3>
                    <p>${content}</p>
                  </div>
                </li>
              `);

            $message.val("");
            $chatContent.scrollTop($chatContent.prop('scrollHeight'));

            $.ajax({
                url: "http://127.0.0.1:6060/chat",
                type: "POST",
                contentType: "application/json; charset=utf-8",
                headers: {
                    "Authorization": `Bearer ${OPENAI_API_KEY}`
                },
                data: JSON.stringify({
                    "model": "gpt-3.5-turbo",
                    "messages": [
                        { "role": "user", "content": `${content}` }
                    ]
                }),
                responseType: 'stream',
                success: function(response) {
                    console.log('response: ', response);
                    const { choices } = response;
                    choices.forEach(choice => {
                        if (choice.message.content.indexOf("\n") >= 0) {
                            choice.message.content = choice.message.content.replace("\n", "<br>");
                        }
                        $messageList.append(`
                          <li class="layui-timeline-item">
                            <i class="layui-icon layui-icon-circle"></i>
                            <div class="layui-timeline-content layui-text chat-bot-message">
                              <h3 class="layui-timeline-title">
                                <i class="layui-icon layui-icon-log"></i>
                              </h3>
                              <p>${choice.message.content}</p>
                            </div>
                          </li>
                        `);
                        $chatContent.scrollTop($chatContent.prop('scrollHeight'));
                    });
                },
                error: function(xhr, status, error) {
                    console.error('error: ', error);
                    alert("提交失败: " + JSON.stringify(content));
                }
            });
        }
    });
</script>
</body>
</html>